import { Injectable, Req } from '@nestjs/common';
import { CreateUserDto } from './dto/create-user.dto';
import { UpdateUserDto } from './dto/update-user.dto';
import { Repository } from 'typeorm';
import { InjectRepository } from '@nestjs/typeorm';
import { User } from './entities/user.entity';
import { LoginUserDto } from './dto/login-user.dto';
import { compareSync, hashSync } from 'bcryptjs';
import { ResultData } from '../../utils/result';

@Injectable()
export class UserService {
    constructor(
        @InjectRepository(User) private readonly user: Repository<User>,
    ) {}
    async register(createUserDto: CreateUserDto) {
        const res = await this.user.findOne({
            where: { account: createUserDto.account },
        });

        if (!res) {
            // 用户密码加盐加密
            createUserDto.password = hashSync(createUserDto.password, 10);
            await this.user.insert(createUserDto);
            return new ResultData(200, '注册成功');
        }

        return new ResultData(500, '账户已被注册');
    }

    async login(login: LoginUserDto) {
        const res = await this.user.findOne({
            where: { account: login.account },
        });
        if (res && compareSync(login.password, res.password)) {
            return new ResultData(200, '登录成功');
        }
        return new ResultData(500, '密码错误');
    }
}
